import numpy as np;
import matplotlib.pyplot as plt;
import sympy as sp;

x = sp.Symbol('x')

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

# 分析函数在无穷远处的极限
def f(x):
    return 1/x

# 计算极限
limit_plus_inf = sp.limit(1/x, x, sp.oo)
limit_minus_inf = sp.limit(1/x, x, -sp.oo)

print(f"x->+∞时函数的极限: {limit_plus_inf}")
print(f"x->-∞时函数的极限: {limit_minus_inf}")

# 可视化
x_vals_positive = np.linspace(1, 100, 400)
x_vals_negative = np.linspace(-100, -1, 400)
y_vals_positive = f(x_vals_positive)
y_vals_negative = f(x_vals_negative)

plt.figure(figsize=(12, 5))

plt.subplot(1, 2, 1)
plt.plot(x_vals_positive, y_vals_positive, 'b-', linewidth=2)
plt.axhline(y=0, color='r', linestyle='--', alpha=0.7, label='y=0')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('x→+∞时f(x)=1/x的极限')
plt.legend()
plt.grid(True, alpha=0.3)

plt.subplot(1, 2, 2)
plt.plot(x_vals_negative, y_vals_negative, 'g-', linewidth=2)
plt.axhline(y=0, color='r', linestyle='--', alpha=0.7, label='y=0')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('x→-∞时f(x)=1/x的极限')
plt.legend()
plt.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()